<?php
require_once("lib.php");

// Basic set has occured.
// Use $_SESSION["authed"] to test for auth
// Use $db to access mysqli API to database


// Not logged in
if ((!$_SESSION["authed"]) || (!isset($_REQUEST["t"]))) {
	header("Location: index.php");
}

$trackID = $_REQUEST["t"];

// Delete Track
if (isset($_GET["delete"])) {
    $stmt = $db->prepare("SELECT id as trackID, trackName, userDescr, tableName, UNIX_TIMESTAMP(trackDate) as trackDate FROM track_tables_info WHERE id = :trackID");
    if ($stmt->execute(array("trackID" => $trackID))) {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        echo $stmt->debugDumpParams();
        exit();
    }
    $tableName = $row["tableName"];
    $db->beginTransaction();
    try {
        $stmt = $db->prepare("DELETE FROM track_tables_info WHERE id = :trackID");
        $stmt->execute(array("trackID" => $trackID));
        $stmt = $db->prepare("DELETE FROM track_tags_link WHERE tracksID = :trackID");
        $stmt->execute(array("trackID" => $trackID));
    } catch (PDOException $e) {
        echo "Failed to delete... you may need to clean up";
        echo $stmt->debugDumpParams();
        $db->rollBack();
        exit();
    }
    $db->commit();
    $db->exec("DROP TABLE $tableName");
    header("Location: index.php");
}

// Update Track
if (isset($_POST["update"])) {
    $stmt = $db->prepare("UPDATE track_tables_info SET trackName = :trackName, userDescr = :userDescr, userPhotoAlbumURL = :userPhotoAlbumURL, userHikeLogURL = :userHikeLogURL, trackFileURL = :trackFileURL WHERE id = :trackID");
    if (!$stmt->execute(array("trackName" => $_POST["trackName"], "userDescr" => $_POST["trackDescr"], "userPhotoAlbumURL" => $_POST["hikePhotoAlbum"], "userHikeLogURL" => $_POST["hikeLog"], "trackID" => $trackID, "trackFileURL" => $_POST["trackFileURL"]))) {
        echo $stmt->debugDumpParams();
    }

    if (isset($_POST["tag"])) {
        $db->beginTransaction();
        $stmt = $db->prepare("DELETE FROM track_tags_link WHERE tracksID = :trackID");
        if (!$stmt->execute(array("trackID" => $trackID))) {
            echo $stmt->debugDumpParams();
            $db->rollBack();
        }
        foreach ($_POST["tag"] as $tagID => $flag) {
            $stmt = $db->prepare("INSERT INTO track_tags_link (trackTagID, tracksID) VALUES (:tagID, :trackID)");
            if (!$stmt->execute(array("tagID" => $tagID, "trackID" => $trackID))) {
                echo $stmt->debugDumpParams();
                $db->rollBack();
            }
        }
        $db->commit();
    }
}

$trackTags = array();
$stmt = $db->prepare("SELECT * FROM track_tags ORDER BY trackTag");
if ($stmt->execute()) {
    while ($row = $stmt->fetch()) {
        $trackTags[$row["id"]] = array("tag" => $row["trackTag"], "linked" => false);
    }
}

$stmt = $db->prepare("SELECT * FROM track_tags_link WHERE tracksID = :trackID");
if ($stmt->execute(array("trackID" => $trackID))) {
    while ($row = $stmt->fetch()) {
        $trackTags[$row["trackTagID"]]["linked"] = true;
    }
}

$stmt = $db->prepare("SELECT id as trackID, trackName, userDescr, tableName, userPhotoAlbumURL, userHikeLogURL, UNIX_TIMESTAMP(trackDate) as trackDate, trackFileURL FROM track_tables_info WHERE id = :trackID");
if ($stmt->execute(array("trackID" => $trackID))) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $rowID = $row["trackID"];
    $trackName = $row["trackName"];
    $trackDate = date("c", $row["trackDate"]);
    $trackDescr = $row["userDescr"];
    $tableName = $row["tableName"];
    $photoAlbumURL = $row["userPhotoAlbumURL"];
    $hikeLog = $row["userHikeLogURL"];
    $trackFileURL = $row["trackFileURL"];
    
    try {
        $row = $db->query("SELECT COUNT(OGR_FID) as count FROM $tableName")->fetch(PDO::FETCH_ASSOC);
        $trackPointCount = $row["count"];
    } catch (PDOException $e) {
        echo "Failed to fetch track count: " . $e->getMessage();
    }
}

$trackTagChecks = "";
foreach ($trackTags as $trackTag => $data) {
        $checked = "";
        $trackTagName = $data["tag"];
        if ($data["linked"] === true) {
            $checked = "CHECKED";
        }
        $trackTagChecks .= <<< HTML
<label class="checkbox">
    <input type="checkbox" name="tag[$trackTag]" $checked>$trackTagName
</label>
HTML;
}

$trackForm = <<< HTML
<form class="form-horizontal" name="formUpdateTrack" id="formUpdateTrack" action="?t=$trackID" method="post">
    <formset>
        <input type="hidden" name="update">
        <legend>Track Details</legend>
        <div class="control-group">
            <label class="control-label" for="trackID">Track ID</label>
            <div class="controls">
                <input type="text" id="trackID" name="trackID" value="$trackID" READONLY>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="trackDate">Track Date</label>
            <div class="controls">
                <input type="text" id="trackDate" name="trackDate" value="$trackDate" READONLY>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="trackPoints">Points in Track</label>
            <div class="controls">
                <input type="text" id="trackPoints" name="trackPoints" value="$trackPointCount" READONLY>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="trackName">Track Name</label>
            <div class="controls">
                <input type="text" id="trackName" name="trackName" value="$trackName">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="trackDescr">Description</label>
            <div class="controls">
                <textarea id="trackDescr" name="trackDescr" rows="2" cols="20">$trackDescr</textarea>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="hikePhotoAlbum">Track Photo Album URL</label>
            <div class="controls">
                <input type="text" id="hikePhotoAlbum" name="hikePhotoAlbum" value="$photoAlbumURL">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="hikeLog">Track Log URL</label>
            <div class="controls">
                <input type="text" id="hikeLog" name="hikeLog" value="$hikeLog">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="trackFileURL">Track File URL</label>
            <div class="controls">
                <input type="text" id="trackFileURL" name="trackFileURL" value="$trackFileURL">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">Tags</label>
            <div class="controls">$trackTagChecks</div>
        </div>
        <button type="submit" class="btn">Update</button>
        <a href="#" data-trackid="$trackID" class="btn deleteConfirm">delete</a>
    </formset>
</form>
HTML;

$htmlTitle = "Hikes and Things: edit track";
echo <<<CONTENT
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>$htmlTitle</title>
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
        <link href="style.css" rel="stylesheet">
        $analytics
    </head>
    <body>
        <div class="navbar navbar-static">
            <div class="navbar-inner">
                <div class="container" style="width: auto;">
                    <a class="brand" href="#">Edit Track</a>
                    <ul class="nav" role="navigation">
                        <li class="divider-vertical"></li>
                        <li><a href="index.php">Tracks</a></li>
                        <li class="divider-vertical"></li>
                        <li><a href="trackDetails.php?t=$trackID">View Track</a></li>
                    </ul>
                    <ul class="nav pull-right">
                        <li class="divider-vertical"></li>
                        <li>$logInOut</li>
                    </ul>
                </div>
            </div>
        </div>
        $trackForm
        <script src="jquery-1.9.1.min.js"></script>
        <script src="jquery.validate.min.js"></script>
        <script src="additional-methods.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
        <script src="bootbox.min.js"></script>
        <script>
            $(document).ready(function() {
                $("#formUpdateTrack").validate({
                    rules: {
                        hikePhotoAlbum: {
                            url: true
                        },
                        hikeLog: {
                            url: true
                       }, 
                       trackName: "required"
                    }
                });
                $(document).on("click", ".deleteConfirm", function(e) {
                    var trackID = $(this).data("trackid");
                    bootbox.confirm("Are you sure?", function(result) {
                        if (result) {
                            window.open("?delete&t=" + trackID, "_self", null, true);
                        }
                    });
                });
            });
        </script>
    </body>
</html>
CONTENT;
?>
